package org.example.demo.service.userService.impl;

import org.example.demo.dto.UpdateAvatarParam;
import org.example.demo.service.userService.UserAccountService;
import org.example.mbg.mapper.UserMapper;
import org.example.mbg.model.User;
import org.example.mbg.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户登录注册service
 */
@Service
public class UserAccountServiceImpl implements UserAccountService {

    @Autowired
    private UserMapper userMapper;

    public Long userLogin(String openid) {
        UserExample ue = new UserExample();
        ue.createCriteria().andWxopenidEqualTo(openid);
        List<User> res = userMapper.selectByExample(ue);
        if (res.size() > 0) {
            return res.get(0).getId();
        } else {
            return this.userRegisterServiceWithWx(openid);
        }
    }

    public Long userRegisterServiceWithWx(String wxOpenid) {
        User u = new User();
        u.setPassword("password");
        u.setPhone("13877389486");
        u.setUsername("wx");
        u.setWxopenid(wxOpenid);
        u.setAvatar("https://pic2.zhimg.com/v2-77b1a31dc62d9e00abd0ea6cdaba5c83_xll.jpg");
        u.setBalance(new BigDecimal(100000L));
        u.setAddress("陕西省西安市碑林区");
        userMapper.insertSelective(u);
        return userLogin(wxOpenid);
    }


    public String updateAvatar(UpdateAvatarParam updateAvatarParam) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(updateAvatarParam.getUser_id());
        User u = new User();
        u.setAvatar(updateAvatarParam.getUrl());
        u.setUsername(updateAvatarParam.getNickname());
        userMapper.updateByExampleSelective(u, userExample);
        return "ok";
    }

    @Override
    public BigDecimal getBalance(Long userId) {
        return userMapper.selectByPrimaryKey(userId).getBalance();
    }

}
